package cn.bdqn.controller.sys;

import cn.bdqn.entity.SysLog;
import cn.bdqn.service.sys.SysJournalService;
import cn.bdqn.service.sys.UserService;
import cn.bdqn.utils.IpUtiles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.Enumeration;

/**
 * @ProjectName: ycbdqn
 * @Package: cn.bdqn.controller.sys
 * @Author: huat
 * @Date: 2020/3/5 16:26
 * @Version: 1.0
 */
@Controller
public class LoginController {
    @Autowired
    UserService userService;
    @Autowired
    SysJournalService sysLogService;
    @RequestMapping("intoLogin")
    public String intoLogin() {
        return "login";
    }

    @RequestMapping("loginFail")
    public String loginFail() {
        return "login_fail";
    }

    @RequestMapping("loginOut")
    public String loginOut() {
        return "login";
    }

    @RequestMapping("jumpIndex")
    public String jumpIndex(HttpSession session) {
        int result = userService.updateSessionByUserId(session);
        if (0 < result) {
            //记录用户登陆操作
            SysLog sysLog=new SysLog();
            sysLog.setUsername(SecurityContextHolder.getContext().getAuthentication().getName());
            sysLog.setCreateDate(new Date());
            HttpServletRequest request=((ServletRequestAttributes) RequestContextHolder
                    .getRequestAttributes()).getRequest();
            sysLog.setIp(IpUtiles.getRealIp(request));
            sysLog.setOperation("登陆成功");
            sysLog.setMethod("login");
            sysLogService.saveSysLog(sysLog);
            return "redirect:"+request.getContextPath()+"/sys/user/index";
        } else {
            Enumeration em = session.getAttributeNames();//得到session中所有的属性名
            while (em.hasMoreElements()) {
                session.removeAttribute(em.nextElement().toString());//遍历删除session中所有值
            }
        }
        return "redirect: intoLogin";
    }
}
